<?php
namespace app\admin\controller;
use think\Request;
use \think\Session;
use \think\Cookie;
use \think\Cache;
use \user\Auth;
use think\Controller;

class User extends Controller
{
    protected $beforeActionList = [
        'first' =>  ['except'=>'login,logout'],
    ];

    protected function first()
    {
        Cookie::init(['prefix'=>'admin_','path'=>'/','httponly'=>true]);
        $token = Cookie::get('token');
        $request = Request::instance();
        $check_res = Auth::check($token,true,Session::get('id'),$request->controller(),$request->action());
        if($check_res['resCode'] == -8){
            Session::delete('id');
            Session::delete('username');
            Session::delete('username_dsp');
            Cookie::delete('token');
            format(-999,$check_res['msg']);
        }else if ($check_res['resCode'] != 2){
            format(-2,$check_res['msg']);
        }
    }

    public function login()
    {
        $request = Request::instance();
        $username = $request->post('username', '', 'SAFE_REPLACE,REMOVE_XSS');
        $password = $request->post('password');

        if(empty($username)){
            format(-1,"请输入用户名");
        }

        if(empty($password)){
            format(-1,"请输入密码");
        }

        $result = Auth::login($username,$password);

        if($result['retCode'] == 2) {
            if ($result['data']['resCode']!=2) {
                format(-2, $result['data']['msg']);
            }
            $user = $result['data']['data'];
            if (isset($user['id'], $user['username'], $user['username_dsp'], $user['sessionId'])) {
                Session::set('id', $user['id']);
                Session::set('role_id', $user['role_id']);
                Session::set('username', $user['username']);
                Session::set('username_dsp', $user['username_dsp']);

                Cookie::init(['prefix' => 'admin_', 'path' => '/', 'httponly' => true]);
                Cookie::set('token', $user['sessionId']);

                $redis = Cache::store('redis');
                $redis->rm('menu_list_'.$user['role_id']);

                format(0, "登录成功！");
            } else {
                format(-2, '登录失败');
            }
        }else {
            format(-2, $result['msg']);
        }

    }

    public function logout(){

        Cookie::init(['prefix' => 'admin_', 'path' => '/', 'httponly' => true]);
        $token = Cookie::get('token');

        Session::delete('id');
        Session::delete('username');
        Session::delete('username_dsp');
        Cookie::delete('token');

        if(empty($token)){
            format(0, "success");
        }

        Auth::logout($token);

        format(0, "success");
    }

    public function getUser()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $id = intval($id);
        if ($id > 0) {
            $params = array(
                'function' => Auth::AUTH_MODULE . ".admin." . "getUserById",
                'data' => array(
                    'id' => $id
                )
            );
            $param = array(
                'data' => json_encode($params)
            );
            $result = Auth::makeRequest(Auth::AUTH_URL, $param);
            $result = json_decode($result['result'], true);
            if ($result['retCode'] == 2 && $result['data']['resCode'] == 2) {
                format(0, 'success', $result['data']['data']);
            }
        }
        format(-2, 'fail');

    }

    public function userList()
    {
        $request = Request::instance();
        $page = $request->post('page');
        $pageSize = $request->post('ps');
        $sort = $request->post('sort', '', 'SAFE_REPLACE,REMOVE_XSS');
        $username = $request->post('username', '', 'SAFE_REPLACE,REMOVE_XSS');

        $page = intval($page);
        $pageSize = intval($pageSize);

        if (empty($page)) {
            $page = 1;
        }

        if (empty($pageSize)) {
            $pageSize = 20;
        }

        switch ($sort) {
            case 'id_desc' :
                $order = array('id' => 'desc');
                break;
            case 'id_asc' :
                $order = array('id' => 'asc');
                break;
            case 'status_desc' :
                $order = array('status' => 'desc');
                break;
            case 'status_asc' :
                $order = array('status' => 'asc');
                break;
            case 'ct_asc' :
                $order = array('create_time' => 'asc');
                break;
            default :
                $order = array('create_time' => 'desc');
                break;
        }

        $params = array(
            'function' => Auth::AUTH_MODULE . ".admin." . "getUserList",
            'data' => array(
                'page' => $page,
                'pageSize' => $pageSize,
                'order' => $order,
                'username' => $username
            )
        );
        $param = array(
            'data' => json_encode($params)
        );
        $result = Auth::makeRequest(Auth::AUTH_URL, $param);
        $result = json_decode($result['result'], true);
        if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
            $data = $result['data']['data'];
            foreach ($data['list'] as $index => $list) {
                unset($data['list'][$index]['password']);
            }
            $ret = array(
                'userList' => $data['list'],
                'amount' => $data['amount'],
                'page' => $data['page'],
                'pageSize' => $data['pageSize']
            );
            format(0, 'success', $ret);
        }
        format(-2, 'fail');
    }

    public function addUser()
    {
        $request = Request::instance();
        $password = $request->post('password');
        $username_dsp = $request->post('username_dsp', '', 'SAFE_REPLACE,REMOVE_XSS');
        $checkPass = $request->post('check_pass');
        $username = $request->post('username', '', 'SAFE_REPLACE,REMOVE_XSS');
        if ($request->has('status')) {
            $status = $request->post('status');
        }
        if (empty($password) || empty($username_dsp) || !isset($status) || empty($username) || empty($checkPass)) {
            format(-2, "信息不完整");
        }

        if (!empty($status) && $status == 'true') {
            $status = 1;
        } else {
            $status = 2;
        }

        $password = md5($password);
        if (md5($checkPass) !== $password) {
            format(-2, "两次输入密码不正确");
        }
        $params = array(
            'function' => Auth::AUTH_MODULE . ".admin." . "register",
            'data' => array(
                'username' => $username,
                'username_dsp' => $username_dsp,
                'status' => $status,
                'password' => $password
            )
        );
        $param = array(
            'data' => json_encode($params)
        );
        $result = Auth::makeRequest(Auth::AUTH_URL, $param);
        $result = json_decode($result['result'], true);

        if (!empty($result['retCode'] == 2)) {
            if ($result['data']['resCode'] == 2) {
                format(0, '添加成功', $result['data']['data']);
            } else {
                format(-2, $result['data']['msg']);
            }
        }
        format(-2, '添加失败');
    }

    public function editUser()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $password = $request->post('password');
        $username_dsp = $request->post('username_dsp','', 'SAFE_REPLACE,REMOVE_XSS');
        $checkPass = $request->post('check_pass');
        $username = $request->post('username','', 'SAFE_REPLACE,REMOVE_XSS');
        if ($request->has('status')) {
            $status = $request->post('status');
        }

        if (empty(intval($id)) || empty($username_dsp) || !isset($status) || empty($username)) {
            format(-2, "信息不完整");
        }

        if (!empty($status) && $status == 'true') {
            $status = 1;
        } else {
            $status = 2;
        }
        if(!empty($password) || !empty($checkPass)) {
            $password = md5($password);
            if (md5($checkPass) !== $password) {
                format(-2, "两次输入密码不正确");
            }
        }
        $params = array(
            'function' => Auth::AUTH_MODULE . ".admin." . "editUser",
            'data' => array(
                'id' => intval($id),
                'username' => $username,
                'username_dsp' => $username_dsp,
                'status' => $status
            )
        );
        if(!empty($password)){
            $params['data']['password'] = $password;
        }
        $param = array(
            'data' => json_encode($params)
        );
        $result = Auth::makeRequest(Auth::AUTH_URL, $param);
        $result = json_decode($result['result'], true);

        if (!empty($result['retCode'] == 2)) {
            if ($result['data']['resCode'] == 2) {
                format(0, '更新成功', $result['data']['data']);
            } else {
                format(-2, $result['data']['msg']);
            }
        }
        format(-2, '更新失败');
    }

    public function delUser()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $id = intval($id);
        if ($id > 0) {
            $params = array(
                'function' => Auth::AUTH_MODULE . ".admin." . "delUser",
                'data' => array(
                    'id' => intval($id)
                )
            );
            $param = array(
                'data' => json_encode($params)
            );
            $result = Auth::makeRequest(Auth::AUTH_URL, $param);
            $result = json_decode($result['result'], true);

            if (!empty($result['retCode'] == 2)) {
                if ($result['data']['resCode'] == 2) {
                    format(0, '删除成功');
                } else {
                    format(-2, $result['data']['msg']);
                }
            }
        }
        format(-2, '删除失败');

    }

}
